<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable style="width: 200px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="退款编号" prop="refundNo">
        <el-input v-model="queryParams.refundNo" placeholder="请输入退款编号" clearable style="width: 200px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="退款状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择退款状态" clearable>
          <el-option v-for="item in refundStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['order:refund:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="() => handleDelete()"
          >删除</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="退款编号" align="center" prop="refundNo" />
      <el-table-column label="订单编号" align="center">
        <template #default="scope">
          <el-link type="primary" @click="handleOrderDetail(scope.row.order)">{{ scope.row.order?.orderNo }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="订单金额" align="center">
        <template #default="scope">
          <span>¥{{ scope.row.order?.actualAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退款金额" align="center">
        <template #default="scope">
          <span>¥{{ scope.row.refundAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退款类型" align="center" prop="refundType">
        <template #default="scope">
          <el-tag :type="getRefundTypeTag(scope.row.refundType) as 'success' | 'warning' | 'info'">
            {{ getRefundTypeLabel(scope.row.refundType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="退款原因" align="center" prop="reason" :show-overflow-tooltip="true" />
      <el-table-column label="退款状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="getRefundStatusTag(scope.row.status) as 'success' | 'warning' | 'info' | 'danger'">
            {{ getRefundStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="处理时间" align="center" prop="handleTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.handleTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理结果" align="center" prop="handleResult" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            v-if="scope.row.status === 0"
            v-hasPermi="['order:refund:approve']"
            link
            type="primary"
            icon="Check"
            @click="() => handleApprove(scope.row)"
            >同意退款</el-button
          >
          <el-button v-hasPermi="['order:refund:edit']" link type="primary" icon="Edit" @click="() => handleUpdate(scope.row)">修改</el-button>
          <el-button v-hasPermi="['order:refund:remove']" link type="primary" icon="Delete" @click="() => handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />

    <!-- 添加或修改订单退款对话框 -->
    <el-dialog v-model="open" :title="title" width="500px" append-to-body>
      <el-form ref="refundFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单编号" prop="orderId">
          <el-input v-model="form.orderNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="退款金额" prop="refundAmount">
          <el-input-number v-model="form.refundAmount" :precision="2" :step="0.01" placeholder="请输入退款金额" />
        </el-form-item>
        <el-form-item label="退款类型" prop="refundType">
          <el-select v-model="form.refundType" placeholder="请选择退款类型">
            <el-option v-for="item in refundTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="退款原因" prop="reason">
          <el-input v-model="form.reason" type="textarea" placeholder="请输入退款原因" />
        </el-form-item>
        <el-form-item label="退款状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择退款状态">
            <el-option v-for="item in refundStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理结果" prop="handleResult">
          <el-input v-model="form.handleResult" type="textarea" placeholder="请输入处理结果" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="orderDetailVisible" title="订单详情" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ currentOrder?.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">¥{{ currentOrder?.actualAmount }}</el-descriptions-item>
        <el-descriptions-item label="优惠金额">¥{{ currentOrder?.discountAmount }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">
          <el-tag>{{ currentOrder?.payType === 1 ? '微信支付' : '支付宝' }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="支付时间">{{ parseTime(currentOrder?.payTime) }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getOrderStatusTag(currentOrder?.status) as 'success' | 'warning' | 'info' | 'danger'">
            {{ getOrderStatusLabel(currentOrder?.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="完成时间">{{ parseTime(currentOrder?.completeTime) }}</el-descriptions-item>
        <el-descriptions-item label="取消时间">{{ parseTime(currentOrder?.cancelTime) }}</el-descriptions-item>
        <el-descriptions-item label="取消原因" :span="2">{{ currentOrder?.cancelReason }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentOrder?.remark }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 退款处理对话框 -->
    <el-dialog v-model="handleVisible" :title="'退款处理'" width="500px" append-to-body>
      <el-form ref="handleFormRef" :model="handleForm" :rules="handleRules" label-width="80px">
        <el-form-item label="处理结果" prop="handleResult">
          <el-input v-model="handleForm.handleResult" type="textarea" placeholder="请输入处理结果" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitHandle">确 定</el-button>
          <el-button @click="cancelHandle">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { OrderRefundVO, OrderRefundQuery, OrderRefundForm } from '@/api/order/refund/types';
import { listOrderRefund, getOrderRefund, addOrderRefund, updateOrderRefund, delOrderRefund } from '@/api/order/refund';
import { parseTime } from '@/utils/ruoyi';
import { ElMessage, ElMessageBox } from 'element-plus';
import { OrderVO } from '@/api/order/order/types';

// 退款类型选项
const refundTypeOptions = [
  { value: 1, label: '全额退款' },
  { value: 2, label: '部分退款' }
];

// 退款状态选项
const refundStatusOptions = [
  { value: 0, label: '待处理' },
  { value: 1, label: '处理中' },
  { value: 2, label: '已完成' },
  { value: 3, label: '已拒绝' }
];

// 获取退款类型标签
const getRefundTypeLabel = (value: number) => {
  return refundTypeOptions.find((item) => item.value === value)?.label || '未知';
};

// 获取退款类型标签样式
const getRefundTypeTag = (value: number) => {
  const map: Record<number, string> = {
    1: 'success',
    2: 'warning'
  };
  return map[value] || 'info';
};

// 获取退款状态标签
const getRefundStatusLabel = (value: number) => {
  return refundStatusOptions.find((item) => item.value === value)?.label || '未知';
};

// 获取退款状态标签样式
const getRefundStatusTag = (value: number) => {
  const map: Record<number, string> = {
    0: 'info',
    1: 'warning',
    2: 'success',
    3: 'danger'
  };
  return map[value] || 'info';
};

// 订单状态选项
const orderStatusOptions = [
  { value: 0, label: '待支付' },
  { value: 1, label: '已支付' },
  { value: 2, label: '已发货' },
  { value: 3, label: '已完成' },
  { value: 4, label: '已取消' },
  { value: 5, label: '已退款' }
];

// 获取订单状态标签
const getOrderStatusLabel = (value?: number) => {
  return orderStatusOptions.find((item) => item.value === value)?.label || '未知';
};

// 获取订单状态标签样式
const getOrderStatusTag = (value?: number) => {
  const map: Record<number, string> = {
    0: 'info',
    1: 'warning',
    2: 'warning',
    3: 'success',
    4: 'danger',
    5: 'danger'
  };
  return map[value || 0] || 'info';
};

const loading = ref(true); // 遮罩层
const ids = ref<number[]>([]); // 选中数组
const single = ref(true); // 非单个禁用
const multiple = ref(true); // 非多个禁用
const showSearch = ref(true); // 显示搜索条件
const total = ref(0); // 总条数
const list = ref<OrderRefundVO[]>([]); // 列表数据
const title = ref(''); // 弹出层标题
const open = ref(false); // 是否显示弹出层

const queryParams = ref<OrderRefundQuery>({
  pageNum: 1,
  pageSize: 10
});

const form = ref<OrderRefundVO>({});
const rules = ref({
  orderId: [{ required: true, message: '订单编号不能为空', trigger: 'blur' }],
  refundAmount: [{ required: true, message: '退款金额不能为空', trigger: 'blur' }],
  refundType: [{ required: true, message: '退款类型不能为空', trigger: 'change' }],
  reason: [{ required: true, message: '退款原因不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '退款状态不能为空', trigger: 'change' }]
});

// 订单详情相关
const orderDetailVisible = ref(false);
const currentOrder = ref<OrderVO>();

// 退款处理相关
const handleVisible = ref(false);
const handleFormRef = ref();
const handleForm = ref({
  id: undefined as number | undefined,
  handleResult: ''
});

const handleRules = ref({
  handleResult: [{ required: true, message: '处理结果不能为空', trigger: 'blur' }]
});

/** 查询订单退款列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listOrderRefund(queryParams.value);
    console.log(res);
    list.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

/** 取消按钮 */
const cancel = () => {
  open.value = false;
  reset();
};

/** 表单重置 */
const reset = () => {
  form.value = {};
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10
  };
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: OrderRefundVO[]) => {
  ids.value = selection.map((item) => item.id!);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = '添加订单退款';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: OrderRefundVO) => {
  reset();
  const id = row?.id || ids.value[0];
  const res = await getOrderRefund(id);
  form.value = res.data;
  open.value = true;
  title.value = '修改订单退款';
};

/** 提交按钮 */
const submitForm = async () => {
  const refundFormRef = ref();
  await refundFormRef.value.validate();
  if (form.value.id) {
    await updateOrderRefund(form.value as OrderRefundForm);
    ElMessage.success('修改成功');
  } else {
    await addOrderRefund(form.value as OrderRefundForm);
    ElMessage.success('新增成功');
  }
  open.value = false;
  getList();
};

/** 删除按钮操作 */
const handleDelete = async (row?: OrderRefundVO) => {
  const refundIds = row?.id ? [row.id] : ids.value;
  await ElMessageBox.confirm('是否确认删除订单退款编号为"' + refundIds + '"的数据项?');
  await delOrderRefund(refundIds);
  getList();
  ElMessage.success('删除成功');
};

// 查看订单详情
const handleOrderDetail = (order?: OrderVO) => {
  currentOrder.value = order;
  orderDetailVisible.value = true;
};

/** 同意退款按钮操作 */
const handleApprove = (row: OrderRefundVO) => {
  handleForm.value = {
    id: row.id,
    handleResult: '',
    orderId: row.orderId,
    orderNo: row.orderNo,
    userId: row.userId,
    refundNo: row.refundNo,
    refundAmount: row.refundAmount,
    refundType: row.refundType,
    reason: row.reason
  };
  handleVisible.value = true;
};

/** 取消处理 */
const cancelHandle = () => {
  handleVisible.value = false;
  resetHandle();
};

/** 表单重置 */
const resetHandle = () => {
  handleForm.value = {
    id: undefined,
    handleResult: ''
  };
};

/** 提交处理 */
const submitHandle = async () => {
  await handleFormRef.value.validate();
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');

  const data = {
    ...handleForm.value,
    status: 2, // 设置为已完成
    handleTime: `${year}-${month}-${day} ${hours}:${minutes}:${seconds}` // 使用标准格式：YYYY-MM-DD HH:mm:ss
  };
  await updateOrderRefund(data as OrderRefundForm);
  ElMessage.success('处理成功');
  handleVisible.value = false;
  getList();
};

onMounted(() => {
  getList();
});
</script>
